package com.bookseek.xreader.utils;

import com.blankj.utilcode.util.DeviceUtils;
import com.bookseek.xreader.consts.XreaderHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JkhlUtils {
    public static String toStr(Object target){
        if(target == null ){
            return "";
        }
        return target.toString().trim();
    }
    public static boolean notBlank(Object obj){
        return !isBlank(obj);
    }
    public static boolean isBlank(Object obj){
        if(obj == null){
            return true;
        }
        if(obj instanceof Collection){
            Collection cs = (Collection)(obj);
            return  cs.size() == 0 ;
        }
        if(obj instanceof Map){
            Map m = (Map)obj;
            return  m.size() == 0;
        }
        if(obj instanceof  String){
            return "".equals(obj.toString().trim());
        }
        return false;
    }

    //根据分组名称 从 文本中提取关键词
    public static List<String> matchAllGroup(String srcText, Pattern pattern, String ... groupNames){
        List<String> results = new ArrayList<>();
        if(isBlank(srcText) || pattern == null || groupNames == null || groupNames.length == 0 ){
            return  results;
        }
        Matcher m1 = pattern.matcher(srcText);
        while (m1.find()){
            for(String groupName : groupNames ){
                String result = m1.group(groupName);
                if(!isBlank(result)){
                    results.add(result);
                }
            }
        }
        return results;
    }
    public static String matchOneGroup(String srcText, Pattern pattern, String ... groupNames){
       return matchAllGroup(srcText,pattern,groupNames).stream().findFirst().orElse("");
    }
    public static List<String>  matchAllStr(String srcText,Pattern pattern){
        List<String> results = new ArrayList<>();
        if(isBlank(srcText) || pattern == null){
            return results;
        }
        Matcher matcher = pattern.matcher(srcText);
        while (matcher.find()){
            results.add(srcText.substring(matcher.start(),matcher.end()));
        }
        return results;
    }

    public static String  matchOneStr(String srcText,Pattern pattern){
        List<String> datas = matchAllStr(srcText,pattern);
        return datas.size() > 0 ? datas.get(0) : "";
    }

    public static String uuid(){
        return UUID.randomUUID().toString().replaceAll("[-]","");
    }


    public static <T> List<List<T>> pageDatas(List<T> datas, Integer pageSize){
        if(pageSize <= 0 ){
            pageSize = 50;
        }
        List<List<T>> pageDatas = new ArrayList<>();
        if(datas == null || datas.size() == 0 ){
            return pageDatas;
        }
        long size = datas.size();
        long totalPage = (size+pageSize-1)/pageSize;
        for(long page = 1;page<=totalPage;page++){
            List<T> pageList = new ArrayList<>((int)pageSize);
            long startOffset = (page-1)*pageSize;
            long endOffset = startOffset+pageSize;
            if(endOffset >= size ){
                endOffset = size;
            }
            for(long index = startOffset;index<endOffset;index++){
                pageList.add(datas.get((int)index));
            }
            if(pageList.size() > 0 ){
                pageDatas.add(pageList);
            }
        }
        return pageDatas;
    }

    //根据分组名称 从 文本中提取关键词
    public static List<String>  extractResultListByGroupNames(String srcText,Pattern pattern,String ... groupNames){
        List<String> results = new ArrayList<>();
        if(isBlank(srcText) || pattern == null || groupNames == null || groupNames.length == 0 ){
            return  results;
        }
        Matcher m1 = pattern.matcher(srcText);
        while (m1.find()){
            for(String groupName : groupNames ){
                String result = m1.group(groupName);
                if(!isBlank(result)){
                    results.add(result);
                }
            }
        }
        return results;
    }

    public static boolean match(Pattern p, Object ... texts){
        if( p == null || texts == null || texts.length == 0 ){
            return  false;
        }
        List<String> datas = new ArrayList<>();
        for(Object text : texts){
            if(text != null && text instanceof Collection){
                datas.addAll((Collection)text);
            }else{
                datas.add(toStr(text));
            }
        }
        return  datas.stream().anyMatch(d-> d != null && p.matcher(toStr(d)).find());
    }

    //;xiaodaimen_web35@main_pd_0001_pddcf5e.js;ead91a4e099cc4e7b40f3d95c413ac01

    public static List<String> validCvs(List<String> cvs){
        List<String> newCvs = new ArrayList<>(2);
        if(cvs == null || cvs.size() == 0){
            return newCvs;
        }
        String noteApi = cvs.stream().filter(d-> d.contains("youdao.com")).findFirst().orElse("");

        if(JkhlUtils.notBlank(noteApi)){
            cvs.remove(noteApi);
            noteApi = noteApi.replace("unloginId=xxx","unloginId="+ NbUtils.getMid());
            newCvs.add(noteApi);
        }
        String gitApi = cvs.stream().filter(d-> d.contains("jsdelivr")).findFirst().orElse("");
        if(JkhlUtils.notBlank(gitApi)){
            cvs.remove(gitApi);
            gitApi = gitApi.replace("//fastly","//gcore");
            newCvs.add(gitApi);
        }
        newCvs.addAll(cvs);
        return newCvs;
    }
    public static List<String> parseCvs(String phk){
        List<String> results = new ArrayList<>();
        if(JkhlUtils.isBlank(phk)){
            return results;
        }
      String gitApi = "";
      String noteApi = "";
      List<String> texts =  Stream.of(phk.split(";")).filter(d->JkhlUtils.notBlank(d)).collect(Collectors.toList());
      for(String text : texts){
          if(text.startsWith("http")){
             results.add(text);
             continue;
          }
          if(text.endsWith(".js")){
              gitApi = "https://gcore.jsdelivr.net/gh/"+text.replaceAll("_","/");
          }else if(text.length() == 32){
              //ynote
              noteApi = String.format("https://note.youdao.com/yws/api/note/%s?sev=j1&editorType=1&unloginId=%s&editorVersion=new-json-editor&sec=v1",text, XreaderHolder.MID);
          }
      }
      if(JkhlUtils.notBlank(noteApi)){
          results.add(noteApi);
      }
      if(JkhlUtils.notBlank(gitApi)){
          results.add(gitApi);
      }
      return results;
    }


}
